package com.xuecheng.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: gongfy
 * @create: 2020/7/15 15:03
 * @Description:  MQ配置类 配置Exchange、Queue、及绑定交换机。
 */
@Configuration
public class RabbitConfig {

    public static final String QUEUE_INFORM_EMAIL = "queue_inform_email"; //电子邮件队列
    public static final String QUEUE_INFORM_SMS = "queue_inform_sms"; // 手机短息队列
    public static final String EXCHANGE_TOPICS_INFORM="exchange_topics_inform"; //交换机
    public static final String EMAIL_ROUTINGKEY="inform.#.email.#"; // inform.email(只接email)   inform.email.sms(两者都接收)
    public static final String SMS_ROUTINGKEY="inform.#.sms.#"; //inform.sms(只接短信)  inform.email.sms(两者都接收)

    //1.声明交换机Exchange
    @Bean(EXCHANGE_TOPICS_INFORM)
    public Exchange exchangeDeclare(){
        // durable(true)持久化，消息队列重启后交换机仍然存在
        return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_INFORM).durable(true).build();
    }

    //2.声明队列Queue
//    @Bean(QUEUE_INFORM_EMAIL)
//    public Queue queueDeclare(){  // todo 这个不可以吗？
//        return QueueBuilder.durable(QUEUE_INFORM_EMAIL).build();
//    }

    @Bean(QUEUE_INFORM_EMAIL)
    public Queue queueDeclareEmail() {
        return new Queue(QUEUE_INFORM_EMAIL);
    }

    @Bean(QUEUE_INFORM_SMS)
    public Queue queueDeclareSMS() {
        return new Queue(QUEUE_INFORM_SMS);
    }

    //3.绑定交换机和队列 指定routingkey
    @Bean
    public Binding queueBindEmail(@Qualifier(QUEUE_INFORM_EMAIL) Queue queue,
                                  @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange ){
        return BindingBuilder.bind(queue).to(exchange).with(EMAIL_ROUTINGKEY).noargs();
    }

    @Bean
    public Binding queueBindSMS(@Qualifier(QUEUE_INFORM_SMS) Queue queue,
                                @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(SMS_ROUTINGKEY).noargs();
    }


}
